<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModeljacandidates extends JModel
{
    var $_data;
    var $_table;
    var $_pagination;
    var $_fieldListEdit;
    var $_table_name = 'ja_resumes';
    var $_fieldList;
    
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    
     function getItems($where_more=''){
     	
		global $mainframe, $jbconfig, $option;
    	
    	$db = JFactory::getDBO ();

		$request = $_REQUEST;
		$filter_field_keys = array();
		if($request){
			$filter_field_keys = array_keys($request);
		}
		
		$statistics = array ();
		$statistics ['approved'] = JRequest::getVar ( 'filter_approved' );
		$statistics ['created_date'] = JRequest::getVar ( 'filter_duration' );
		
		$limit = $mainframe->getUserStateFromRequest( JBCOMNAME .".jacandidates.limit",	'limit',	'20',	'int' );
		$limitstart = $mainframe->getUserStateFromRequest( JBCOMNAME .".jacandidates.limitstart",	'limitstart',	'0',	'int' );
		
    	$db = JFactory::getDBO();
    	
    	$search	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jacandidates.search",			'search',			'',				'string' );
		$search = trim(JString::strtolower ( $search ));
		
		$published	= $mainframe->getUserStateFromRequest( $option.".jacandidates.published",	'published',		'',	'cmd' );
		$approved	= $mainframe->getUserStateFromRequest( $option.".jacandidates.approved",	'approved',		'',	'cmd' );
		
		$this->getFieldList();
    	$this->getEditFieldList(' and f.frontend_hidden=0');
    	
    	$filter_order = JRequest::getVar('filter_order', 'a.id');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.".jacandidates.filter_order_Dir",	'filter_order_Dir',	"DESC",	'word' );				
    	
    	$where = array();
    	
    	// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
				
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();	
     	
		$join_clause_table['rs'] =  "\n INNER JOIN #__users as rs ";
		$join_clause_field['rs'] = " ON rs.id=a.user_id ";
		
     	if($search){
        	$subwhere [] .= " (rs.username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        	 					" OR rs.email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        						")";
        }
		
		JB_Admin_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search, $subwhere);			
		
        if($published!='' && $published==0){
        	$where_clause[] = ' (	a.published=0 or ISNULL(a.published) )';
        }
        elseif($published==1){
        	$where_clause[] = 'a.published=1' ;
        }
        
		if($approved!='' && $approved==0){
        	$where_clause[] = ' (	a.approved=0 or ISNULL(a.approved) )';
        }
        elseif($approved==1){
        	$where_clause[] = 'a.approved=1' ;
        }
                
     	switch ($statistics['created_date']) 	{
    		case 'today':
    			$where_clause[] = '(DATEDIFF(a.created_date,now())=0)';
    			break;
    		case 'week':
    			$where_clause[] = '(EXTRACT(WEEK FROM a.created_date)=EXTRACT(WEEK FROM now()))';
    			break;	
    		case 'month':
    			$where_clause[] = '(EXTRACT(MONTH FROM a.created_date)=EXTRACT(MONTH FROM now()))';
    			break;
    	}    	
				
		if ($filter_order) {
			$orderby =$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = " a.id DESC";
		}
     	
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
        
        /* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );//echo $db->getQuery();exit;
		$total = $db->loadResult ();
		
		jimport ( 'joomla.html.pagination' );		
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.approved, a.published, a.published, rs.id, rs.name, rs.username, rs.email" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.id desc';
		$db->setQuery ( $query, $limitstart, $limit );	
					
		$items = $db->loadObjectList ();
		
		return $items;	
    
    }          
    
    /**
    * Get field table instance
    * @return JTable Configuration table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('ja_resumes', 'JobBoardTable');
        	
        }
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Remove email record
	* @return Number of removed records
	*/
	function remove(){
	    JRequest::checkToken() or jexit( 'Invalid Token' );

		$db 			=& JFactory::getDBO();
		$currentUser 	=& JFactory::getUser();
		$acl			=& JFactory::getACL();
		$cid 			= JRequest::getVar( 'cid', array(), '', 'array' );

		JArrayHelper::toInteger( $cid );

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a User to delete', true ) );
		}

	    $msg = '';
	    if($cid){
		    foreach ($cid as $id)
			{
				// check for a super admin ... can't delete them
				$objectID 	= $acl->get_object_id( 'users', $id, 'ARO' );
				$groups 	= $acl->get_object_groups( $objectID, 'ARO' );
				$this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );
	
				$success = false;
				if ( $this_group == 'super administrator' )
				{
					$msg = JText::_( 'You cannot delete a Super Administrator' );
				}
				else if ( $id == $currentUser->get( 'id' ) )
				{
					$msg = JText::_( 'You cannot delete Yourself!' );
				}
				else if ( ( $this_group == 'administrator' ) && ( $currentUser->get( 'gid' ) == 24 ) )
				{
					$msg = JText::_( 'WARNDELETE' );
				}
				else
				{
					$user =& JUser::getInstance((int)$id);
					$count = 2;
	
					if ( $user->get( 'gid' ) == 25 )
					{
						// count number of active super admins
						$query = 'SELECT COUNT( id )'
							. ' FROM #__users'
							. ' WHERE gid = 25'
							. ' AND block = 0'
						;
						$db->setQuery( $query );
						$count = $db->loadResult();
					}
	
					if ( $count <= 1 && $user->get( 'gid' ) == 25 )
					{
						// cannot delete Super Admin where it is the only one that exists
						$msg = "You cannot delete this Super Administrator as it is the only active Super Administrator for your site";
					}
					else
					{
						// delete user
						$user->setParam('usertype','Guest');
						$user->save(true);
//						$user->delete();
						
						
						/* Delete permission record */
				        $query = "DELETE FROM #__ja_permissions WHERE user_id = $id";
				        $db = &JFactory::getDBO();
				        $db->setQuery($query);
				        $db->query();
						
				        /* Delete profile record */
				        $query = "DELETE FROM #__ja_resumes WHERE user_id = $id";
				        $db = &JFactory::getDBO();
				        $db->setQuery($query);
				        $db->query();
				        
				        clearDataForJobSeeker($id);
				        
						JRequest::setVar( 'task', 'remove' );
						JRequest::setVar( 'cid', $id );
					}
				}
			}
			$row = $this->_getTable();
			$row->reorder();
			return $msg;
	    }	    
	}
	
	/**
	* Get configuration item
	* @return JobboardTableja_candidates Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}
		
        $table =& $this->_getTable(); 
		$table->_tbl_key = 'user_id';
		// Load the current item if it has been defined
		$edit	= JRequest::getVar('view',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		$user 		=& JUser::getInstance( $cid[0] );
		if(!$user->id ){
			$cid[0] = 0;
		}			
		
		if ($cid[0]>0) {
			$table->load($cid[0]);
		}
		
	    $item = $table;
	    return $item;	    
	}
	
	/**
    * @desc Get all fields that will be displayed on edit form
    */
    function getEditFieldList($where = ''){        
        if(!$this->_fieldListEdit){	       
	        $this->_fieldListEdit = getEditFieldList($this->_table_name);
        }   
		return $this->_fieldListEdit ;       
    }
    
    function getFieldList($where=''){    	    	
    	if( !$this->_fieldList){	       
	        $this->_fieldList = getFieldList($this->_table_name); 
    	}
    	return  $this->_fieldList;
    }
    
	/**
	 * Get list email by list ids
	 *
	 */
	function getEmails(){
		$cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if(!$cid) return '';
	    
	    $cid = implode(',', $cid);
	    
	    $emails = '';
	    
	    $db = &JFactory::getDBO();
	    $query = "select email from #__ja_candidates where id in ($cid)";
	    $db->setQuery($query);	
		$emails = $db->loadResultArray(0);
		if ($emails) {
			$emails = implode(',', $emails);
		}
		return $emails;
	}
	
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store($row=null){
		$controller = 'jaresumes';
	    // Initialize variables
		$db		=& JFactory::getDBO();
		if(!$row)	$row	=& $this->getItem();
		$state = $row->approved;
		$post	= $this->getState('request');
			
		if (!$row->bind( $post )) {
            echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		if ($row->spec_field)
		{
           	if (!assign_spec_field($controller,$row))
           		return false;
		}
        if ($row->editor_field)
			assign_editor_field($row);   		
		if (!$row->check())
		    {
			    return false;
		    }		
		
		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		$new_state = $row->approved;
		if (($state!=$new_state) && ($new_state=='1'))
		{
//			prepare_data('Job Seeker User',$row->user_id);
			updateUserType(JBJOB_SEEKER_USER,$row->user_id);
			$this->status_changing_email($row->id, $row->user_id,'JobSeekerApprovedEmail');
		}
		if (($state!=$new_state) && ($new_state=='0'))
		{
			
//			prepare_data('Employer User',$row->user_id);
			updateUserType('Guest',$row->user_id);
			$this->status_changing_email($row->id, $row->user_id,'JobSeekerNonApprovedEmail');
		}
		$row->checkin($row->user_id);
		
		return $row->user_id;
	}
		   
    
    function dopublish($value){
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());		
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_resumes"
		. "\n SET published = " . intval( $value )
		. "\n WHERE id IN ( $ids )"
		;//echo $query;exit;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
	
    function getLocation(){
    	$db		=& JFactory::getDBO();
    	$query = "SELECT id, name FROM #__ja_location WHERE (parent_id = 0 OR ISNULL(parent_id)) AND published = 1";
        $db->setQuery($query);
        $locations = $db->loadObjectList();
        return $locations;
    }
    
    function doblock($block){
       // Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$db 			=& JFactory::getDBO();
		$acl			=& JFactory::getACL();
		$currentUser 	=& JFactory::getUser();

		$cid 	= JRequest::getVar( 'cid', array(), '', 'array' );

		JArrayHelper::toInteger( $cid );

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a User to '.$this->getTask(), true ) );
		}
		foreach ($cid as $id)
		{
			// check for a super admin ... can't delete them
			$objectID 	= $acl->get_object_id( 'users', $id, 'ARO' );
			$groups 	= $acl->get_object_groups( $objectID, 'ARO' );
			$this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );

			$success = false;
			if ( $this_group == 'super administrator' )
			{
				$msg = JText::_( 'You cannot block a Super Administrator' );
			}
			else if ( $id == $currentUser->get( 'id' ) )
			{
				$msg = JText::_( 'You cannot block Yourself!' );
			}
			else if ( ( $this_group == 'administrator' ) && ( $currentUser->get( 'gid' ) == 24 ) )
			{
				$msg = JText::_( 'WARNBLOCK' );
			}
			else
			{
				$user =& JUser::getInstance((int)$id);
				$count = 2;

				if ( $user->get( 'gid' ) == 25 )
				{
					// count number of active super admins
					$query = 'SELECT COUNT( id )'
						. ' FROM #__users'
						. ' WHERE gid = 25'
						. ' AND block = 0'
					;
					$db->setQuery( $query );
					$count = $db->loadResult();
				}

				if ( $count <= 1 && $user->get( 'gid' ) == 25 )
				{
					// cannot delete Super Admin where it is the only one that exists
					$msg = "You cannot block this Super Administrator as it is the only active Super Administrator for your site";
				}
				else
				{
					$user =& JUser::getInstance((int)$id);
					$user->block = $block;
					$user->save();

					if($block)
					{
						JRequest::setVar( 'task', 'block' );
						JRequest::setVar( 'cid', array($id) );
						$msg = JText::_('Update successfully !');
						// delete user acounts active sessions
//						$this->logout();
					}
				}
			}
		}
		return $msg;
    }

    function download(){
        $cid = JRequest::getVar( 'cid', array(0), '', 'array' );
        $fieldname = JRequest::getVar('field_name');
		JArrayHelper::toInteger($cid, array(0));
        $table =& $this->_getTable(); 
		$table->_tbl_key = 'id';
        $table->load($cid[0]);
        $file_name = explode('/',$table->{$fieldname}); 
        if( $table->{$fieldname}) {
        	$file = JPATH_SITE.DS.str_replace('/','\\',$table->{$fieldname});
	        if (file_exists(str_replace('/','\\',$file)))
	        	$file = str_replace('/','\\',$file);
	        else 
        		$file = str_replace('\\','/',$file);
           
        	if ( ! file_exists($file) ){
        		echo JText::_("<script language='javascript'> alert('".JText::_("File not found on the Server")."'); </script>");
        		return ;
        	}
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
        }
    }
    
     function doapprove($task)
    {
    	JRequest::checkToken() or jexit( 'Invalid Token' );

		$db 			=& JFactory::getDBO();
		
		$cid 	= JRequest::getVar( 'cid', array(), '', 'array' );
		$approve = ($task=='approve')?1:0;
		$email_template = ($task=='approve')?'JobSeekerApprovedEmail':'JobSeekerNonApprovedEmail';
		$new_usertype = ($task=='approve')?JBJOB_SEEKER_USER:'Guest';
		JArrayHelper::toInteger( $cid );

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a User to '.$task(), true ) );
		}
		if (is_array($cid))
			$str_cid = implode(',',$cid);
		else 	
			$str_cid = $cid;
		$query = "UPDATE #__ja_resumes SET approved=$approve WHERE user_id IN ($str_cid)";
		$db->setQuery($query);
		$db->query();
		
		$query = "SELECT user_id,id FROM #__ja_resumes WHERE user_id IN ($str_cid)";
		$db->setQuery($query);
		$obj_UserId = $db->loadObjectList();
		for ($i=0;$i<count($obj_UserId);$i++)
		{
			updateUserType($new_usertype,$obj_UserId[$i]->user_id);
			$this->status_changing_email($obj_UserId[$i]->id,$obj_UserId[$i]->user_id,$email_template);
		}
		
			
		$msg = ($task=='approve')?JText::_('Successfully approved resume(s). User(s) can now perform their permission on the site.'):JText::_('Successfully disapproved the resume(s). User(s) have not been permitted to perform any activities on the site.');
		return $msg;
    } 
    
    function status_changing_email($resume_id, $user_id, $email_template)  
    {
    	$user = JFactory::getUser($user_id);
    	$arr_link = array();
    	$arr_link['users'] = $user_id;
    	$arr_link['ja_resumes'] = $resume_id;
    	$mail = get_EmailTemplate($arr_link,$email_template);
    	if ($mail)
    	{
    		sendmail($user->email,$user->name,$mail->subject,$mail->content,'',$mail->EmailFromAddress, $mail->EmailFromName);
    	}
    }
    
    function remove_attach()
    {
    	remove_attach('ja_resumes');

    }
}
?>